<template>
	<view class="content" :class="'theme-'+theme">
	<my-search-header v-model="keyword" :showRightBtn="false" @back="returnIndex" placeholder="输入订单号或商品名称"
		:inputConfig="{disabled:true}" @click="toSearch">
		<text @click="clickShowFilter">筛选</text>
	</my-search-header>
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{current: tabCurrentIndex === index}"
			 @click="tabClick(index)">
				<text style="text-align: center" v-if="navList[index].num===0">{{item.text}}</text>
				<text style="padding-left: 10rpx;" v-else>{{item.text}}</text>
				<uni-badge class="badge themeBgColor" v-if="index!==0" :text="navList[index].num" size="small"></uni-badge>
			</view>
		</view>
				<image class="top-back" src="../../static/top-back.png" v-show="showToTop" @click="toTop()"></image>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view :scroll-top="listScrollTop" class="list-scroll-content" scroll-y @scrolltolower="getMore"  @scroll="topScroll">
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>

					<!-- 订单列表 -->
					<view v-for="(item,index) in tabItem.orderList" :key="index" class="order-item">
						<view v-if="item.orders.length>1" class="order-list">
							<!-- <view>订单编号：{{item.sn}}</view> -->
							<!-- <img class="split-img" src="../../static/orderIcon1.03c4621f.jpg"/> -->
							<text class="split-title">订单号:{{item.sn}}</text>
							<view class="split-time">{{item.createTime}}</view>
							<!-- <view>订单总额：{{item.total}}</view> -->
							<view class="description">您订单中的商品属于不同于协议或供应商，故拆分为以下订单分开配送</view>
						</view>
						<view v-for="(order,orderIndex) in item.orders" :key="orderIndex">
							<view @click="toDetail(order.sn)">
								<view v-if="item.orders.length==1" class="bottom" style="padding-bottom: 0;">
									<view class="header-txt">
										订单号:{{order.sn}}
									</view>
								</view>
								<view class="i-top b-b">
									<text v-if="supplierInfoShow" class="eticon eticon-gongyingshang themeTextColor" style="margin-left: 0;margin-right: 16rpx;font-size: 20px;"></text>
									<view class="time">
										<text v-if="supplierInfoShow">{{order.supplierName}}</text>
										<online-service v-if="supplierCustomerGroup[order.supplierId]" @service="toService(order,order.supplierId)"></online-service>
									</view>
									<u-image style="margin-left: 10rpx;" v-if="order.protocolType==='eplus'&&order.productLogo!=''" :src="order.productLogo" width="100rpx" height="50rpx"></u-image>
									<text class="state themeTextColor" v-if="order.cancelApplyInfo && order.cancelApplyInfo.curStatus==1">取消待确认</text>
									<text v-else class="state themeTextColor">{{statusData[order.status]}}</text>
								</view>
								<view class="goods-box-single" v-for="(goodsItem, goodsIndex) in order.items" :key="goodsIndex">
									<image class="goods-img" :src="goodsItem.thumbnail" mode="aspectFill"></image>
									<view class="right">
										<text class="title clamp">{{goodsItem.productName}}</text>
										<view class="attr-box">
											<text class="attr"> x {{goodsItem.num}}</text>
<!--											<view class="action" v-if="(order.status === 'completed'||order.status==='partialShipment')&&item.procureSource!='oldData'&&order.returnStatus != '02'&&canSaleAfter(goodsItem)" @click.stop="clickAftersale(order,goodsItem,1)">申请售后</view>-->
											<view class="action" v-if="canSaleAfter(item,order,goodsItem)" @click.stop="clickAftersale(order,goodsItem,1)">申请售后</view>
										</view>
										<text class="price">{{goodsItem.price|twoBitMoney}}</text>
									</view>
								</view>

								<view class="bottom">
									<view class="time-text">{{order.createTime}}</view>
									<view class="price-box">
										<!-- 共
										<text class="num">{{order.items.length}}</text>
										件 -->
										金额
										<text class="price">￥{{order.amount|twoBitMoney}}</text>
									</view>
								</view>
							</view>

							<view class="action-box b-t" v-if="order.status === 'waitSupConfirm'||order.status ==='waitAudit'">
								<view class="action-btn" @click="openPopup(order,'cancel')" v-if="(!order.cancelApplyInfo || order.cancelApplyInfo.curStatus!=1)">取消订单</view>
								<view class="action-btn recom themeBorderColor themeTextColor" v-if="enableOneMoreOrder" @click="addToCart(order)">再来一单</view>
							</view>
							<!-- <view class="action-box b-t" v-else-if="order.status === 'unShipped'||order.status === 'waitPayment'"> -->
							<view class="action-box b-t" v-else-if="order.status === 'unShipped'">
<!--								<view class="action-btn" @click="openPopup(order,'cancel')" v-if="(!order.cancelApplyInfo || order.cancelApplyInfo.curStatus!=1)">取消订单</view>-->
								<view class="action-btn recom themeBorderColor themeTextColor" v-if="enableOneMoreOrder" @click="addToCart(order)">再来一单</view>
							</view>
							<view class="action-box b-t" v-else-if="order.status === 'shipped'||order.status==='partialShipment'">
								<view class="action-btn recom themeBorderColor themeTextColor" @click="beforeConfirm(order)">确认收货</view>
								<view class="action-btn" @click="toLogistics(order.id)">查看物流</view>
								<view class="action-btn recom themeBorderColor themeTextColor" v-if="enableOneMoreOrder" @click="addToCart(order)">再来一单</view>
							</view>
							<view class="action-box b-t" v-else-if="order.status === 'completed'">
								<view class="action-btn" v-if="enableOneMoreOrder" @click="addToCart(order)">再来一单</view>
								<!-- <view class="action-btn" @click="clickAftersale(item,2)">申请售后</view> -->
								<view class="action-btn recom themeBorderColor themeTextColor" v-if="order.isHasReview" @click="toSeeEvaluate(order)">查看评价</view>
								<view class="action-btn recom themeBorderColor themeTextColor" v-else @click="toEvaluate(order)">评价</view>
							</view>
							<view class="action-box b-t" v-else-if="order.status === 'cancelled'||order.status==='commitFail'||order.status==='auditReject'||order.status==='refuse'">
								<view class="action-btn recom themeBorderColor themeTextColor" v-if="enableOneMoreOrder" @click="addToCart(order)">再来一单</view>
							</view>
							<view class="action-box b-t" v-else-if="order.status==='waitPayment'">
							<!-- <view class="action-box b-t" v-else-if="order.status==='waitPay'"> -->
								<view class="action-btn" @click="openPopup(order,'cancel')" v-if="(!order.cancelApplyInfo || order.cancelApplyInfo.curStatus!=1)">取消订单</view>
								<!-- <view class="action-btn recom">去支付</view> -->
							</view>
						</view>
						<!-- </view> -->
					</view>

					<uni-load-more :status="tabItem.loadingType"></uni-load-more>

				</scroll-view>
			</swiper-item>
		</swiper>
		<uni-popup ref="showcancel" :type="type" :mask-click="false">
			<view class="uni-tip">
				<text class="uni-tip-title">取消订单</text>
				<view class="popup-content uni-tip-content">
					<view class="order-info">订单编号：{{curOrder.sn}}</view>
					<view class="cancel-info">
						<view class="cancel-hint required">取消原因：</view>
						<input disabled @click="clickShowCancelSelect" placeholder="请选择取消原因" class="cancel-content" v-model="mainReason.label"/>
						<u-select @confirm="confirmCancelSelect" v-model="showCancelSelect" :list="cancelDict" value-name="code" label-name="name"></u-select>
					</view>
					<view class="cancel-info">
						<view class="cancel-hint">补充描述：</view>
						<textarea class="cancel-content" style="min-height: 60px;height: auto;line-height: 20px;" placeholder-class="ph" placeholder="请填写补充描述，有助于供应商了解您取消的原因"
							v-model="cancelReason" />
					</view>
				</view>
				<view class="uni-tip-group-button">
					<text class="uni-tip-button" @click="close('cancel')">取消</text>
					<text class="uni-tip-button confirm themeBgColor themeBorderColor" @click="cancelOrder()">确定</text>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="showconfirm" :type="type" :mask-click="false">
			<view class="uni-tip">
				<text class="uni-tip-title">提示</text>
				<text class="uni-tip-content">请确认是否已收到货？</text>
				<view class="uni-tip-group-button">
					<text class="uni-tip-button" @click="close('confirm')">取消</text>
					<text class="uni-tip-button confirm themeBgColor themeBorderColor" @click="confirmReceive()">确定</text>
				</view>
			</view>
		</uni-popup>
		<u-popup mode="center" width="90%" :mask="true" zIndex="1000" v-model="receivePopupShow" border-radius="10" :closeable="true">
			<order-track :logisticsList="logisticsList" :logisticsTab="logisticsTab" @confirm="clickConfirm" :dictData="dictData"></order-track>
		</u-popup>
    <u-popup v-model="showFilter" mode="right" width="70%" class="filter">
			<view style="padding-bottom: 100rpx;">
				<view class="filter_h">
					下单时间
				</view>
				<view class="filter_w">
					<view class="filter_w_item date" :class="{btnFrameAlpha:filterParams.dateType===1}" @click="changeDate(1)">
						近1个月
					</view>
					<view class="filter_w_item date" :class="{btnFrameAlpha:filterParams.dateType===3}" @click="changeDate(3)">
						近3个月
					</view>
					<view class="filter_w_item date" :class="{btnFrameAlpha:filterParams.dateType===6}" @click="changeDate(6)">
						近6个月
					</view>
				</view>
				<view class="filter_w" style="justify-content: center;">
					<view class="filter_w_item range">
						<input placeholder="开始日期" @click="clickShowDatePicker(1)" disabled v-model="filterParams.startTime" placeholder-class="ph" />
					</view>
					<view class="filter_w_split">-</view>
					<view class="filter_w_item range">
						<input placeholder="结束日期" @click="clickShowDatePicker(2)" disabled v-model="filterParams.endTime" placeholder-class="ph" />
					</view>
				</view>
				<view class="filter_h">
					供应商
				</view>
				<view class="filter_w">
					<view class="filter_w_item" @click="changeSupplier(supplier.supplierId)" :class="{btnFrameAlpha:filterParams.supplierIds.includes(supplier.supplierId)}" v-for="supplier in supplierList" :key="supplier.supplierId">
						{{supplier.supplierName}}
					</view>
				</view>
			</view>
			<view class="filter_b">
				<u-button size="medium" @click="resetFilterParams">重置</u-button>
				<u-button size="medium" type="error" class="themeBgColor" @click="confirmFilterParams">确认</u-button>
			</view>
		</u-popup>
		<u-picker v-if="showDatePicker" v-model="showDatePicker" mode="time" :params="dateParams" safe-area-inset-bottom :defaultTime="computedDefaultTime" @confirm="confirmDate"></u-picker>
		<online-service v-if="isShowCustomerService" is-platform></online-service>
	</view>
</template>

<script>
	import OnlineService from '../../components/online-service/online-service.vue'
	import OrderTrack from '../../components/order-track/order-track.vue'
	import moment from 'moment'
	import MySearchHeader from '@/components/my-search-header/my-search-header.vue'
	import {  goback } from "@/common/utils/navigateBack.js";
	import copyButton from '../../components/copy.vue'
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import empty from "@/components/empty";
	import {
		getOrderList,
		cancelOrder,
		getAllStatus,
		buyAgain,
		confirmReceipt,
		getLogistics,
		applyAftersale,
		getDict,
		getCountByStatus,
		getWaitReviewCount,
		orderMasterSupplierList,
		comfirPreorder
	} from '../../api/order/order.js'
  import { showRuleSupplierInfoShow, qryConfByItemCode, listCustomerGroupBySupplierId} from '@/api/user/user.js'
  import { onlineService } from '../../api/index';
  import UPopup from "../../uview-ui/components/u-popup/u-popup";
  import UButton from "../../uview-ui/components/u-button/u-button";
  import {
		addToCart
	} from '../../api/cart/cart.js'
	export default {
		components: {
      UButton,
      UPopup,
			uniLoadMore,
			empty,
			uniPopup,
			copyButton,
			MySearchHeader,
			OnlineService,
			OrderTrack
		},
		data() {
			return {
				// 筛选参数
				filterParams:{
					startTime: '',
					endTime: '',
					date:[],
					supplierIds:[],
					dateType:-1,
					pickerType:1,
				},
				oldFilterParams:{
					startTime: '',
					endTime: '',
					date:[],
					supplierIds:[],
					dateType:-1,
					pickerType:1,
				},
				searchParams:{},
				// 下单时间选择器
				showDatePicker:false,
				dateParams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				// 供应商列表
				supplierList:[],
				// 筛选弹窗
				showFilter:false,
				// 搜索key
				keyword:'',
				// 取消订单原因字典
				cancelDict:[],
				// 取消原因选择器
				showCancelSelect:false,
				// 取消原因
				mainReason:{},
				limit: 10,
				tabCurrentIndex: 0,
				cancelReason: '',
				type: 'center',
				// 待取消的订单
				toBeCanceledOrder:{},
				statusData:{},
				curOrder: {},
				logisticsList:[],
        logisticsTab:[],
				dictData: {},
        receivePopupShow:false,
        activeItemStyle:{
          color:'#fa436a'
        },
        swiperCurrent:0,
				navList: [{
						status: '',
						text: '全部',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					},
					{
						// status: 'waitPay',
            		status: 'waitAudit',
						text: '审核中',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					},
					{
						status: 'waitSupConfirm',
						text: '待接单',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					},
					{
						status: 'unShipped',
						text: '待发货',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					},
					{
						status: 'shipped',
						text: '待收货',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					},
					{
						status: 'waitReview',
						text: '待评价',
						loadingType: 'more',
						orderList: [],
						page: 1,
						num:0
					}
				],
				// 供应商配置
				supplierInfoShow: true,
				enableOneMoreOrder:true,
				// 供应商在线客服map
				supplierCustomerGroup:{},
				// 是否显示平台客服
				isShowCustomerService:0,
        showToTop: false,
        listScrollTop:0
			};
		},
		onShow(){
			if (getApp().globalData.fromOrderSearch) {
				this.keyword = getApp().globalData.orderSearchKey
				this.loadData()
				getApp().globalData.fromOrderSearch = 0
			}
		},
		computed:{
			computedDefaultTime(){
				const map = {
					1:'startTime',
					2:'endTime'
				}
				return this.filterParams[map[this.filterParams.pickerType]]
			}
		},
		onPageScroll(e) {
					//兼容iOS端下拉时顶部漂移
					this.listScrollTop = e.scrollTop
					this.showToTop = this.listScrollTop > 0 ? true : false
				},
		onLoad(options) {
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			// 初始化是否显示客服
			this.isShowCustomerService = uni.getStorageSync('isShowCustomerService')
			  ? Number(uni.getStorageSync('isShowCustomerService')) : 1
			let simpleName = uni.getStorageSync('enterpriseInfo').simpleDeptName;
			let title = simpleName?simpleName:uni.getStorageSync('enterpriseInfo').name;
			document.title = title||'我的订单'
			// 获取供应商配置
			this.loadSupplierInfoShow();
			// 获取再来一单配置
			this.loadConf()
			this.tabCurrentIndex = +options.state;
			this.loadData()
			this.getStatusData()
			this.loadDictData()
			this.getCount()
			this.loadSupplierList()

		},

		onPullDownRefresh() {
			this.loadData()
		},
		filters:{
			omitWord(value, num=10){
				let number = Number(num)
				if (!value) return ''
				if (value.length > number) {
					return value.slice(0, number) + '...'
				}
				return value
			}
		},
		methods: {
			canSaleAfter(item,order,goodsItem){
			  let saleAfterStep = 'unShipped'
        let hiddleBtn=true;
        order.items.forEach(obj=>{
          if(obj.saleAfterCompleted>0){
            hiddleBtn =false;
          }
        })
        if (saleAfterStep == 'unShipped') {
          if (order.status == 'completed'){
            return item.procureSource != 'oldData'
                && order.returnStatus != '02'
                && order.productType !='4'
                // &&item2.productType !='3'
                // && item3.num != item3.returnNum
                && goodsItem.num - goodsItem.alreadySaleNum > 0
          }else {
            return ',unShipped,partialShipment'.indexOf(order.status)>0
                && item.procureSource != 'oldData'
                && order.returnStatus != '02'
                && order.productType !='4'
                // &&item2.productType !='3'
                // && item3.num != item3.returnNum
                && goodsItem.num != goodsItem.alreadySaleNum + goodsItem.shippedNum
            // && item3.num - item3.alreadySaleNum > 0
          }
          // console.log('status',',unShipped,partialShipment,completed,'.indexOf(order.status)>0
          //     && item.procureSource != 'oldData'
          //     && order.returnStatus != '02'
          //     &&order.productType !='4'
          //     // &&item2.productType !='3'
          //     && hiddleBtn
          //     && goodsItem.num != goodsItem.returnNum)
          // return ',unShipped,partialShipment,completed,'.indexOf(order.status)>0
          //     && item.procureSource != 'oldData'
          //     && order.returnStatus != '02'
          //     &&order.productType !='4'
          //     // && goodsItem.num != goodsItem.returnNum
          //     && goodsItem.num - goodsItem.alreadySaleNum > 0
        }
				// 仅退款
				// const canRefundNum = item.num - item.shippedNum - item.unDeliverSaleAfterNum
				// // 售后数量
				// const saleAfterNum = item.receiveNum - item.receiveSaleafterNum - item.confirmedUnReceiveSaleAfterNum
				// return canRefundNum>0||saleAfterNum>0
			},
			toTop() {
							this.listScrollTop = 0;
							this.showToTop = false
						},
						topScroll(e) {
							this.listScrollTop = e.target.scrollTop
							this.showToTop = this.listScrollTop > 0 ? true : false
						},
      addCart(item) {
        console.log(item)
        let pType;
        let qType;
        if (item.goodsSourceType === 0) {
          pType = '02';
          qType = 1;
        } else {
          pType = '01';
          qType = 2;
        }
        const good = {
          protocolGoodsId: item.goodsId,
          protocolId: item.protocolId,
          protocolType: pType,
          remainAmount: 1
        }
        /* const params = {
          areaId: uni.getStorageSync('areaId'),
          bizDeptId: uni.getStorageSync('bizDeptInfo').deptId,
          goods: [good],
          isqueryAmount: true,
          queryType: qType
        } */
        const params = {
          areaId: uni.getStorageSync('areaId'),
          goodsId: item.goodsId||item.id,
          num: 1
        }
        let userAreaId = uni.getStorageSync('areaId')
        if (userAreaId) {
          params['areaId'] = userAreaId
        } else {
          params['areaId'] = uni.getStorageSync('tenantAreaId')
        }
        addToCart(params).then(res => {
          if (res.code === 0) {
            this.$util.msg('加入购物车成功')
          } else {
            this.$util.msg(res.message)
          }
        })

      },
      // 点击楼层商品跳转到详情页
      navToFloorItemDetail(good) {
		if(good.status!='onsale') return
        const id = good.goodsId||good.id;
        uni.navigateTo({
          url: `/pages/product/product?id=${id}`
        })
      },
			toService(order,supplierId){
				let content = `订单编号:${order.sn}\n供应商订单号:${order.thirdSn}\n订单总额:${order.total}\n订单内商品:`+order.items.map(item =>item.productName).join('、')
				onlineService({ "type": "order", "content": content,"vendorId": this.supplierCustomerGroup[supplierId]}).then(res=>{
					if(res.code === 0){
						window.location.href=res.data
					}
				})
			},
			getSupplierCustomerGroup(ids){
				ids = [...new Set(ids)]
				ids.forEach(id => {
					listCustomerGroupBySupplierId({}, 'supplierIds[]=' + id).then(res => {
						if (res.code === 0) {
							this.supplierCustomerGroup = {
								...this.supplierCustomerGroup,
								...res.data
							}
						}
					})
				})
			},
			returnIndex() {
				goback()
			},
			loadDictData() {
				const param = {
					data: '["DELIVERY_TYPE","CANCEL_ORDER_REASON"]'
				}
				getDict(param).then(res => {
					if (res.code === 0) {
						let data = res.data.DELIVERY_TYPE
						data.forEach(item => {
							this.dictData[item.code] = item.name;
						})
						this.cancelDict = res.data.CANCEL_ORDER_REASON
					} else {
						this.$util.msg(res.message)
					}
				})
			},
			// 获取再来一单配置
			loadConf(){
				const deptInfo = uni.getStorageSync('deptinfo')[0]
				qryConfByItemCode({code:'enableOneMoreOrder',
				tenant_id: deptInfo.tenantId,
				dept_code: deptInfo.deptCode}).then(res=>{
					if(res.code===0){
						this.enableOneMoreOrder = res.data.val == '1'
					}
				})
			},
			  // 获取是否屏蔽供应商信息配置
			  async loadSupplierInfoShow() {
				await showRuleSupplierInfoShow().then(res => {
				  if (res.code === 0) {
					this.supplierInfoShow = !res.data;
				  }
				})
			  },
			//获取订单列表
			loadData(source) {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];

				// if (source === 'tabChange' && navItem.loaded === true) {
				// 	//tab切换只有第一次需要加载数据
				// 	return;
				// }
				if (navItem.loadingType === 'loading') {
					//防止重复加载
					return;
				}
				navItem.loadingType = 'loading';

				let total = 0;
				let orderList;
				const param = {
					page: 1,
					limit: this.limit,
					status: navItem.status,
					keyword: this.keyword,
					...this.searchParams
				}
				getOrderList(param).then(res => {
					if (res.code === 0) {
						const supplierIds = []
						res.data.records.forEach(master=>{
							 supplierIds.push(...master.orders.map(i=>i.supplierId))
						})
						navItem.orderList = res.data.records;
						//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
						this.$set(navItem, 'loaded', true);
						total = parseInt(res.data.total)
						//判断是否还有数据， 有改为 more， 没有改为noMore
						if (navItem.orderList.length === total) {
							navItem.loadingType = 'noMore'
						} else {
							navItem.loadingType = 'more';
						}
						navItem.page = 2;
						this.getSupplierCustomerGroup(supplierIds)
					} else {
						this.toast(res.message)
						navItem.loadingType = 'more';
					}
				})
			},
			service(type, open) {
				this.type = type;
				this.$nextTick(() => {
					this.$refs['show' + open].open();
				})
			},
			getStatusData(){
				getAllStatus().then(res=>{
					if(res.code===0){
						this.statusData=res.data
					}
				})
			},
			getMore() {
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				if (navItem.loadingType === 'loading') {
					//防止重复加载
					return;
				}
				navItem.loadingType = 'loading';
				let total = 0;
				let orderList;
				const param = {
					page: navItem.page,
					limit: this.limit,
					status: navItem.status,
					keyword:this.keyword,
					...this.searchParams
				}
				getOrderList(param).then(res => {
					if (res.code === 0) {
						const supplierIds = []
						res.data.records.forEach(master=>{
							 supplierIds.push(...master.orders.map(i=>i.supplierId))
						})
						orderList = res.data.records;
						orderList.forEach(item => {
							navItem.orderList.push(item);
						})
						//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
						this.$set(navItem, 'loaded', true);
						this.getSupplierCustomerGroup(supplierIds)
						total = parseInt(res.data.total)
						//判断是否还有数据， 有改为 more， 没有改为noMore
						if (navItem.orderList.length === total) {
							navItem.loadingType = 'noMore'
						} else {
							navItem.loadingType = 'more';
						}
						navItem.page++;
					} else {
						this.toast(res.message)
						navItem.loadingType = 'more';
					}
				})
			},
			toDetail(id){
				uni.navigateTo({
					url: '/pages/order/detail?id='+id
				})
			},
			toast(msg) {
				uni.showToast({
					title: msg,
					duration: 1200,
					mask: false,
					icon: 'none'
				});
			},
			//swiper 切换
			changeTab(e) {
				const index = e.target.current
				const navItem = this.navList[index]
				if(navItem.status==='waitReview'){
					uni.navigateTo({
						url:'/pages/evaluate/list'
					})
					return
				}
				this.tabCurrentIndex = index;
				this.tabCurrentIndex = e.target.current;
				console.log(this.tabCurrentIndex)
				this.loadData('tabChange');
			},
			//顶部tab点击
			tabClick(index) {
				const navItem = this.navList[index]
				if(navItem.status==='waitReview'){
					uni.navigateTo({
						url:'/pages/evaluate/list'
					})
					return
				}
				this.tabCurrentIndex = index;
			},
			// 去评价
			toEvaluate(item){
				let sn = item.sn;
				uni.navigateTo({
					url:`/pages/evaluate/evaluate?sn=${sn}`
				})
			},
      toSeeEvaluate(item){
        let sn = item.sn;
        uni.navigateTo({
          url:`/pages/evaluate/evaluate-detail?sn=${sn}`
        })
      },
			// 申请售后
			clickAftersale(order,item,type){
				let sn = order.sn
				let id = item.id
				let deptName = order.deptName
				const params={
					 orderItemId: id,
					 orderSn: sn,
					 type:type
				}
				applyAftersale(params).then(res=>{
					if (res.code === 0){
						if(res.data){
							uni.navigateTo({
								url:`/pages/aftersale/aftersale?sn=${sn}&id=${id}&deptName=${deptName}&type=${type}`,
							})
						}else {
							this.$util.msg('没有可以发起售后申请商品的数量')
						}
					}else {
						this.$util.msg(res.message)
					}
				})
			},
			//再来一单
			addToCart(item){
				uni.showLoading({
					title: '请稍后'
				})
				const params={
					sn:item.sn
				}
				buyAgain(params).then(res=>{
					if(res.code===0){
						uni.hideLoading();
						uni.switchTab({
							url:'/pages/cart/cart'
						})
					}else{
						uni.hideLoading();
					}
				})
			},
			openPopup(item,type) {
				if (type !== 'log')
				    this.curOrder = item;
				this.service('center', type)
			},
			// 关闭弹窗
			close(type) {
				this.$refs['show' + type].close();
				this.curOrder = {}
				this.cancelReason = ''
			},
			beforeConfirm(item){
				console.log('item',item);
				uni.showLoading({
					title:'加载中'
				})
				const param = {
					id: item.id
				}
				getLogistics(param).then(res => {
					uni.hideLoading()
					if (res.code === 0){
						this.logisticsList = res.data;
						this.logisticsTab = this.logisticsList.map((item,index)=>{return {name:'物流'+(index+1)}})
						if (this.logisticsList.length === 1 && item.status === 'shipped'){
						  this.clickConfirm(this.logisticsList[0])
						}else {
              				this.receivePopupShow = true
						}
					}
				})
			},
			clickConfirm(item){
				const that = this
				uni.showModal({
					title: '提示',
					content: '请确认是否已收到货？',
					confirmColor: that.themeColor,
					success: suc => {
						if (suc.confirm) {
							confirmReceipt({
								id: item.orderId,
								outgoingSn: item.outgoingSn
							}).then(res => {
								if (res.code === 0) {
									that.$util.msg('确认收货成功!')
									that.receivePopupShow = false
									that.loadData()
									that.getCount()
								} else {
									that.$util.msg(res.message)
								}
							})
						}
					}
				})
			},
			// 确认收货
			confirmReceive(){
				let orderId = this.logisticsList[0].orderId;
				let outgoingSn = this.logisticsList[0].outgoingSn;
				uni.showLoading({
					title: '请稍后',
				})
				const params = {
					id: orderId,
					outgoingSn: outgoingSn
				}
				confirmReceipt(params).then(res => {
					if (res.code === 0){
						uni.hideLoading();
						this.$util.msg('确认收货成功!')
						this.curOrder = {}
						setTimeout( () => {
							this.close('confirm')
						}, 600)
						this.loadData()
						this.getCount()
					}else {
						this.$util.msg(res.message)
						uni.hideLoading();
					}
				})
			},
			// 取消订单
			cancelOrder() {
				let reason = this.mainReason.label
				if (!reason) {
					this.$util.msg('请选择取消原因！')
					return;
				}
				if(this.cancelReason){
					reason += `，${this.cancelReason}`
				}
				const params = {
					sn: this.curOrder.sn,
					reason: reason,
        		}
				cancelOrder(params).then(res=>{
					if(res.code===0){
						this.$util.msg('取消成功')
						this.cancelReason = '';
						this.curOrder = {}
						this.mainReason = {}
						this.loadData()
						this.getCount()
						setTimeout( () => {
							this.close('cancel')
						}, 600)
					}else{
						this.$util.msg(res.message)
					}
				})
			},
			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#fa436a';
				switch (+state) {
					case 1:
						stateTip = '待付款';
						break;
					case 2:
						stateTip = '待发货';
						break;
					case 9:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;

						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
			clickShowCancelSelect(){
				if(!this.showCancelSelect)
				this.showCancelSelect = !this.showCancelSelect
			},
			confirmCancelSelect(e){
				if(e.length>0)
					this.mainReason = e[0]
			},
			getCount(){
				getCountByStatus({
					status: 'waitAudit'
				}).then(res => {
					if (res.code === 0) {
						this.navList[1].num = Number(res.data)
					}
				})

				getCountByStatus({
					status: 'waitSupConfirm'
				}).then(res => {
					if (res.code === 0) {
						this.navList[2].num = Number(res.data)
					}
				})

				getCountByStatus({
					status: 'unShipped'
				}).then(res => {
					if (res.code === 0) {
						this.navList[3].num = Number(res.data)
					}
				})

				getCountByStatus({
					status: 'shipped'
				}).then(res => {
					if (res.code === 0) {
						this.navList[4].num = Number(res.data)
					}
				})

				getWaitReviewCount().then(res => {
					if (res.code === 0) {
						this.navList[5].num = Number(res.data)
					}
				})
			},
			// 订单搜索
			toSearch() {
				uni.navigateTo({
					url: '/pages/order/search?key=' + this.keyword
				})
			},
			// 筛选面板
			clickShowFilter(){
				this.showFilter=!this.showFilter
				if(this.showFilter){
					this.filterParams = JSON.parse(JSON.stringify(this.oldFilterParams))
				}
			},
			// 供应商列表
			loadSupplierList(){
				orderMasterSupplierList().then(res=>{
					if(res.code===0){
						this.supplierList = res.data
					}
				})
			},
			// 筛选-供应商
			changeSupplier(id){
				if(this.filterParams.supplierIds.includes(id)){
					this.filterParams.supplierIds.splice(this.filterParams.supplierIds.indexOf(id),1)
				}else{
					this.filterParams.supplierIds.push(id)
				}
			},
			// 筛选-下单时间
			changeDate(type){
				if(type===this.filterParams.dateType){
					this.filterParams.dateType = -1
					this.filterParams.date = []
					return
				}
				this.filterParams.dateType = type
				if(type>0){
					this.filterParams.startTime = ''
					this.filterParams.endTime = ''
					this.filterParams.date = [moment().subtract(type, 'month').format('YYYY-MM-DD'),moment().format('YYYY-MM-DD')]
				}else{
					this.filterParams.date = []
				}
				this.$forceUpdate()
			},
			// 下单时间选择器 type:1 开始日期 - 2 结束日期
			clickShowDatePicker(type){
				this.filterParams.pickerType = type
				this.showDatePicker = true
			},
			confirmDate(e){
				const map = {
					1:'startTime',
					2:'endTime'
				}
				this.filterParams[map[this.filterParams.pickerType]] = e.year+'-'+e.month+'-'+e.day
				this.changeDate(-1)
			},
			toLogistics(id) {
				// uni.navigateTo({
				// 	url: '/pages/express/logistics?id=' + id
				// })
				uni.navigateTo({
					url: '/pages/deliver/deliverLogistic?item='+id
				})
			},
			// 重置筛选
			resetFilterParams(){
				this.filterParams.startTime = ''
				this.filterParams.endTime = ''
				this.filterParams.date = []
				this.filterParams.dateType = -1
				this.filterParams.pickerType = 1
				this.filterParams.supplierIds = []
				this.searchParams = {}
				this.$forceUpdate()
				// this.filterParams = this.oldFilterParams
			},
			// 确认筛选
			confirmFilterParams(){
				let startTime = this.filterParams.date.length>0?this.filterParams.date[0]:this.filterParams.startTime?this.filterParams.startTime:''
				let endTime = this.filterParams.date.length>1?this.filterParams.date[1]:this.filterParams.endTime?this.filterParams.endTime:''
				const params = {
					startTime:startTime?startTime+' 00:00:00':'',
					endTime:endTime?endTime+' 23:59:59':'',
					supplierIds:this.filterParams.supplierIds.join(',')
				}
				this.oldFilterParams = JSON.parse(JSON.stringify(this.filterParams))
				this.showFilter = false
				this.searchParams = params
				this.loadData()
			},
		}
	}
</script>

<style lang="scss">
	page,
	.content {
		background: $page-color-base;
		height: 100%;
	}
	.yticon {
				font-size: 44upx;
				color: #5eba8f;
				margin-right: 16upx;
				line-height: 40upx;
			}
  .budget-title{
    text-align: center;
    font-weight: bold;
    font-size: 16px;
    color: #333;
    padding: 15px;
    border-bottom: 1px solid #e9e9e9;
  }
	.swiper-box {
		height: calc(100% - 40px);
	}

	.list-scroll-content {
		height: 100%;
	}

	// .time-text {
	// 	font-size: 14px;
	// 	float: left;
	// 	position: absolute;
	// 	left: 5px;
	// }

	.navbar {
		display: flex;
		height: 40px;
		padding: 0 5px;
		background: #fff;
		box-shadow: 0 1px 5px rgba(0, 0, 0, .06);
		position: sticky;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 28rpx;
			color: $font-color-dark;
			position: relative;
			text {
				width: 100%;
				text-align: left;
			}
			/deep/.uni-badge{
					line-height: normal;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			.badge {
				position: absolute;
				top: 0;
				right: -10rpx;
				color: #fff;
				background-color: $base-color;
				/* #ifdef MP */
				border-radius: 100px;
				/* #endif */

				text {
					/* #ifdef MP */
					color: #fff;
					background-color: $base-color;
					/* #endif */
				}
			}
			&.current {
				// color: $my-newh5-color;

				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 44px;
					height: 0;
					border-bottom: 4rpx solid $my-newh5-color;
				}
			}
		}
	}

	.uni-tip {
		overflow: hidden;
		.log-content{
			.tabs{
				display: flex;
				// height: 30px;
				width: 100%;
				.tab-item{
					flex: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					height: 100%;
					font-size: 13px;
					color: $font-color-dark;
					position: relative;
					padding-bottom: 10rpx;

					&.current {
						color: $base-color;
						&:after {
							content: '';
							position: absolute;
							left: 50%;
							bottom: 0;
							transform: translateX(-50%);
							width: 34px;
							height: 0;
							border-bottom: 2px solid $base-color;
						}
					}
				}
			}
			.swiper-area{
				width: 100%;
				font-size: 13px;
				.s-item{
						background-color: #fff;
						width: 100%;
						padding: 16rpx 40rpx;
						display: flex;
						flex-direction: column;

						.btn {
							width: 160upx;
							height: 60upx;
							margin: 0;
							padding: 0;
							text-align: center;
							line-height: 60upx;
							font-size: $font-sm + 2upx;
							background: #fff9f9;
							color: $base-color;
							border-radius: 10px;
							border: 0.5px solid $base-color;
						}

						.c-line {
							padding: 10rpx 0;
						}

						.p-line {
							padding: 10rpx 0;
							display: flex;
							justify-content: flex-start;
							// align-items: center;

							.left-side {
								font-size: 13px;
							}

							.track-list {
								padding: 10rpx 0;

								.track-item {
									.time {}

									.day {}

									.content {}
								}
							}
						}
				}
			}
		}
		.popup-content {
			.order-info {
				color: #303133;
				margin-bottom: 16rpx;
			}
			.cancel-info{
				margin-bottom: 16rpx;
				display: flex;
				align-items: center;
				color: #303133;
				.cancel-hint{

					&.required{
						position: relative;
						&::before{
							content: '*';
							position: absolute;
							color: #FF2C5E;
							left: -18rpx;
						}
					}
				}
				input{
					font-size: 28rpx;
				}
				.cancel-content{
					flex: 1;
					padding: 10rpx;
					height: 60rpx;
					border: 2rpx solid #d9d9d9;
					border-radius: 8rpx;
				}
				textarea{
					font-size: 28rpx;
					height: 140rpx;
					min-height: 140rpx;
					max-height: 200rpx;
				}
			}

			.cancel-reason {
				width: 100%;
				padding: 16rpx;
				color: #303133;
				font-size: 14px;
				border: 1px solid #d9d9d9;
			}

			.ph {
				font-size: 28rpx;
				color: #9d9e9e;
			}
		}

		.uni-tip-group-button {
			border-top: none;

			.uni-tip-button {
				border-top: 1px solid #e2e2e2;

				&.confirm {
					border-top: 1rpx solid $base-color;
					border-bottom: 1rpx solid $base-color;
					color: #fff;
					background-color: $base-color;
				}
			}
		}
	}

	.uni-swiper-item {
		height: auto;
	}


	.order-item {
		display: flex;
		flex-direction: column;
		background: #fff;
		margin: 16rpx 16rpx 0 16rpx;
		border-radius: 20rpx;

		.order-list{
			margin: 10rpx;
			border-radius: 10rpx;
			background-color: #fff;
			font-size: 14px;
			.split-title{
				float: left;
				padding-top: 10px;
				color: #909090;
			}
			.split-img{
				height: 50rpx;
				float: left;
				padding-top: 12rpx;

			}
			.split-time{
				text-align: right;
				padding-top: 10px;
				padding-bottom: 10px;
			}
			.description{
				color: black;
			}
			text{
				font-size: 14px;
				color: $font-color-base;
			}
		}

		.i-top {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			height: 80upx;
			padding: 0 20upx;
			font-size: $font-base;
			color: $font-color-dark;
			position: relative;

			.time {
				flex: 1;
				width: 0;
				margin-right: 10rpx;
				display: flex;
				align-items: center;
				text{
					max-width: calc(100% - 54rpx);
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-right: 10rpx;
				}
			}

			.img {
				width: 32upx;
				height: 32upx;
				margin-right: 6upx;
			}


			.state {
				margin-left: 10rpx;
				text-align: right;
			}

			.del-btn {
				padding: 10upx 0 10upx 36upx;
				font-size: $font-lg;
				color: $font-color-light;
				position: relative;

				&:after {
					content: '';
					width: 0;
					height: 30upx;
					border-left: 1px solid $border-color-dark;
					position: absolute;
					left: 20upx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}

		/* 多条商品 */
		.goods-box {
			height: 160upx;
			padding: 20upx 0;
			white-space: nowrap;

			.goods-item {
				width: 120upx;
				height: 120upx;
				display: inline-block;
				margin-right: 24upx;
			}

			.goods-img {
				display: block;
				width: 100%;
				height: 100%;
			}
		}

		/* 单条商品 */
		.goods-box-single {
			display: flex;
			align-items: center;
			padding: 20upx;

			.goods-img {
				display: block;
				width: 120upx;
				height: 120upx;
				background-color: #fff;
				background: url(../../static/error-img-60.png);
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding-left: 20rpx;
				overflow: hidden;

				.title {
					font-size: $font-base;
					color: $font-color-dark;
				}

				.attr-box {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					padding: 10upx 0 10upx 10upx;

					.attr{
						float: left;
						width: fit-content;
					}
					.action {
						float: right;
						width: fit-content;
						height: fit-content;
						padding: 4rpx 16rpx;
						text-align: center;
						font-size: 12px;
						color: $font-color-dark;
						background: #fff;
						border-radius: 20px;
						border: 0.5px solid #C0C4CC;
					}
				}

				.price {
					font-size: $font-base + 2upx;
					color: $font-color-dark;

					&:before {
						content: '￥';
						font-size: $font-sm;
						margin: 0 2upx 0 8upx;
					}
				}
			}
		}

		.bottom{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20upx;
			.time-text {
				font-size: 14px;
			}

			.price-box {
				display: flex;
				justify-content: flex-end;
				align-items: baseline;
				// padding: 20upx 30upx;
				font-size: $font-sm + 2upx;
				color: $font-color-light;

				.num {
					margin: 0 8upx;
					color: $font-color-dark;
				}

				.price {
					font-size: $font-lg;
					color: $base-color;
					margin: 0 2upx 0 8upx;

					// &:before {
					// 	content: '￥';
					// 	font-size: $font-sm;
					// 	margin: 0 2upx 0 8upx;
					// }
					&:after{
						color: $base-color;
						font-size: 15px;
						margin-left: 8rpx;
					}
				}
			}
		}

		// .price-box {
		// 	display: flex;
		// 	justify-content: flex-end;
		// 	align-items: baseline;
		// 	// padding: 20upx 30upx;
		// 	font-size: $font-sm + 2upx;
		// 	color: $font-color-light;

		// 	.num {
		// 		margin: 0 8upx;
		// 		color: $font-color-dark;
		// 	}

		// 	.price {
		// 		font-size: $font-lg;
		// 		color: $font-color-dark;

		// 		// &:before {
		// 		// 	content: '￥';
		// 		// 	font-size: $font-sm;
		// 		// 	margin: 0 2upx 0 8upx;
		// 		// }
		// 	}
		// }

		.action-box {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100upx;
			position: relative;
			padding: 0 20rpx;
		}

		.action-btn {
			width: 160upx;
			height: 60upx;
			margin: 0;
			margin-left: 24upx;
			padding: 0;
			text-align: center;
			line-height: 60upx;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
			background: #fff;
			border-radius: 20px;
			border: 0.5px solid #C0C4CC;

			&:after {
				border-radius: 100px;
			}

			&.recom {
				// background: #fff9f9;
				color: $base-color;
				border: 0.5px solid $base-color;

				&:after {
					border: 0.5px solid $base-color;
				}
			}
		}
	}


	/* load-more */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80upx;
		align-items: center;
		justify-content: center
	}

	.uni-load-more__text {
		font-size: 28upx;
		color: #999
	}

	.uni-load-more__img {
		height: 24px;
		width: 24px;
		margin-right: 10px
	}

	.uni-load-more__img>view {
		position: absolute
	}

	.uni-load-more__img>view view {
		width: 6px;
		height: 2px;
		border-top-left-radius: 1px;
		border-bottom-left-radius: 1px;
		background: #999;
		position: absolute;
		opacity: .2;
		transform-origin: 50%;
		animation: load 1.56s ease infinite
	}

	.uni-load-more__img>view view:nth-child(1) {
		transform: rotate(90deg);
		top: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(2) {
		transform: rotate(180deg);
		top: 11px;
		right: 0
	}

	.uni-load-more__img>view view:nth-child(3) {
		transform: rotate(270deg);
		bottom: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(4) {
		top: 11px;
		left: 0
	}

	.load1,
	.load2,
	.load3 {
		height: 24px;
		width: 24px
	}

	.load2 {
		transform: rotate(30deg)
	}

	.load3 {
		transform: rotate(60deg)
	}

	.load1 view:nth-child(1) {
		animation-delay: 0s
	}

	.load2 view:nth-child(1) {
		animation-delay: .13s
	}

	.load3 view:nth-child(1) {
		animation-delay: .26s
	}

	.load1 view:nth-child(2) {
		animation-delay: .39s
	}

	.load2 view:nth-child(2) {
		animation-delay: .52s
	}

	.load3 view:nth-child(2) {
		animation-delay: .65s
	}

	.load1 view:nth-child(3) {
		animation-delay: .78s
	}

	.load2 view:nth-child(3) {
		animation-delay: .91s
	}

	.load3 view:nth-child(3) {
		animation-delay: 1.04s
	}

	.load1 view:nth-child(4) {
		animation-delay: 1.17s
	}

	.load2 view:nth-child(4) {
		animation-delay: 1.3s
	}

	.load3 view:nth-child(4) {
		animation-delay: 1.43s
	}

	@-webkit-keyframes load {
		0% {
			opacity: 1
		}

		100% {
			opacity: .2
		}
	}
	.filter {
			margin-top: 90rpx;
			font-size: $my-font-size-middle;
			color: #aaa;

			&_b{
				height: 90rpx;
				position: fixed;
				left: 0;
				right: 0;
				bottom: 0;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			&_h {
				padding: 20rpx 20rpx 0 20rpx;
				color: #303133;
			}

			&_w {
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				margin-right: 20rpx;

				&_split {
					line-height: 52rpx;
					margin-top: 20rpx;
					margin-left: 20rpx;
				}

				&_item {
					border-radius: 30rpx;
					margin-left: 20rpx;
					margin-top: 20rpx;
					text-align: center;
					padding: 4rpx 16rpx;
					color: #aaa;
					background-color: #f2f2f2;
					line-height: 40rpx;
					border:2rpx solid transparent;

					.ph{
						color: #aaa;
					}

					&.date {
						width: calc((100% - 60rpx) / 3);
					}

					&.range {
						flex: 1;
						height: 52rpx;

						input {
							font-size: $my-font-size-middle;
							height: 40rpx;
							line-height: 40rpx;
						}
					}
				}
			}
		}

	.cart-icon,
		.top-back {
			width: 80rpx;
			height: 80rpx;
			position: fixed;
			right: 34rpx;
			bottom: 200rpx!important;
			-webkit-overflow-scroll: touch;
			z-index: 100000;
		}
</style>
